package com.psa.dialog;

import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import com.psa.element.ISqlObject;
import com.psa.system.R;
import com.psa.tool.IGeneralEventCallback;
import com.wxw.BaseLibrary.adapter.SpinnerAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author david
 * @date 2016-06-23
 */
public class SingleSelectorDialog extends DialogManager implements View.OnClickListener {
    private Spinner sp_sqlObjects;
    private List<ISqlObject> iSqlObjects = new ArrayList<ISqlObject>();
    private OnSingleItemSelectedListener onSingleItemSelectedListener;
    private IGeneralEventCallback onCancelListener;
    private TextView tv_label;

    public SingleSelectorDialog(Activity parent, List<ISqlObject> objects) {
        parentActivity = parent;
        iSqlObjects = objects;
        initView();
    }

    @Override
    public void setTitle(String title) {
        this.title = title;
    }

    public void setLabel(String label) {
        if (this.tv_label != null) {
            tv_label.setText(label);
        }
    }

    public void setOnSingleItemSelectedListener(OnSingleItemSelectedListener onSingleItemSelectedListener) {
        this.onSingleItemSelectedListener = onSingleItemSelectedListener;
    }

    public void setOnCancelListener(IGeneralEventCallback onCancelListener) {
        this.onCancelListener = onCancelListener;
    }

    @Override
    public View initView() {
        layout = parentActivity.getLayoutInflater().inflate(R.layout.single_selector_layout, null);
        sp_sqlObjects = (Spinner)layout.findViewById(R.id.sp_item);
        tv_title = (TextView)layout.findViewById(R.id.tv_title);
        tv_label = (TextView)layout.findViewById(R.id.tv_label);
        ((Button)layout.findViewById(R.id.btn_ok)).setOnClickListener(this);
        ((Button)layout.findViewById(R.id.btn_cancel)).setOnClickListener(this);
        refreshSqlObjects();
        return layout;
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.btn_cancel) {
            if (onCancelListener!=null) {
                onCancelListener.finished(this, "canceled");
            }
        } else {
            ISqlObject iSqlObject = (ISqlObject)sp_sqlObjects.getSelectedItem();
            if (onSingleItemSelectedListener != null) {
                onSingleItemSelectedListener.onSelected(this, iSqlObject);
            }
        }
        if (dialog!=null) {
            dialog.dismiss();
        }
    }

    private void refreshSqlObjects() {
        SpinnerAdapter<ISqlObject> adapter = new SpinnerAdapter<ISqlObject>(parentActivity, 0, iSqlObjects, R.drawable.dropdown);
        sp_sqlObjects.setAdapter(adapter);
    }

    public interface OnSingleItemSelectedListener{
        void onSelected(Object sender, ISqlObject item);
    }
}
